package com.example.chapter02.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.example.chapter02.ActStartActivity;

/**
 * Author:LiuZejiang
 * Date:2022/10/22  14:28
 * JDK-Version:1.8
 */
public class MyServiceToStart extends Service {

    private Thread workThread;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("onCreate");
        //线程组，需要执行的Runnable对象，线程的名称
        workThread = new Thread(null,backgroundWork,"WorkThread");
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        if(!workThread.isAlive()){
            System.out.println("onStart");
            workThread.start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        workThread.interrupt();
    }

    private Runnable backgroundWork = new Runnable() {
        @Override
        public void run() {
            try {
                while(!Thread.interrupted()){
                    double random = Math.random();
                    System.out.println(random);
                    ActStartActivity.UpdateGUI(random);
                    Thread.sleep(2000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
}
